<?php


namespace app\admin\controller;

use app\logic\DataHelper;
use app\logic\MenuHelper;
use think\facade\Db;
use think\facade\View;
use function think\replace;

class Sys extends Base
{
    public function create_curd() {
        $params = get_all_params();
        $tb_name = $params['tb_name'];
        $columns = Db::query("show columns from $tb_name");
        $first_col = $columns[1]['Field'];
        $objname = $this->tbname_to_objname($tb_name);

        $ctrl  = "";
        $ctrl .= "<?php"."\n";
        $ctrl .= 'namespace app\admin\controller;'."\n";
        $ctrl .= 'use app\logic\DataHelper;'."\n";
        $ctrl .= 'use app\logic\MenuHelper;'."\n";
        $ctrl .= 'use think\facade\Db;'."\n";
        $ctrl .= 'use think\facade\View;'."\n";
        $ctrl .= "class ".$objname." extends Base"."\n";
        $ctrl .= "{"."\n";
        $ctrl .= "    public function index() {"."\n";
        $ctrl .= "        return View::fetch('index');"."\n";
        $ctrl .= "    }"."\n";
        $ctrl .= ""."\n";
        $ctrl .= "    public function save() {"."\n";
        $ctrl .= '        $params = get_all_params();'."\n";
        $ctrl .= ""."\n";
        $ctrl .= "        if (!check_params_empty(['".$first_col."'])) {"."\n";
        $ctrl .= "            return json([ 'code' => -1, 'msg' => '请填写：".$first_col."' ]);"."\n";
        $ctrl .= "        }"."\n";
        $ctrl .= '        if (isset($params["id"]) && $params["id"] > 0) {'."\n";
        $ctrl .= '            DataHelper::update("'.$tb_name.'", "id=".$params["id"], $params);'."\n";
        $ctrl .= "        } else {"."\n";
        $ctrl .= '            DataHelper::add("'.$tb_name.'", $params);'."\n";
        $ctrl .= "        }"."\n";
        $ctrl .= "        return json([ 'code' => 0, 'msg' => '成功' ]);"."\n";
        $ctrl .= "    }"."\n";
        $ctrl .= ""."\n";
        $ctrl .= '    public function edit($id = 0) {'."\n";
        $ctrl .= '        if ($id > 0) {'."\n";
        $ctrl .= '            $entry = DataHelper::find_by_id("'.$tb_name.'", $id);'."\n";
        $ctrl .= "        } else {"."\n";
        $ctrl .= '            $entry = ['."\n";

        foreach ($columns as $col) {
            if (in_array($col['Field'], ['create_time', 'update_time'])) {
                continue;
            }
            if ($col['Field'] == 'id') {
                $ctrl .= "                '".$col['Field']."' => '0',"."\n";
            } else {
                $ctrl .= "                '".$col['Field']."' => '',"."\n";
            }
        }

        $ctrl .= "            ];"."\n";
        $ctrl .= "        }"."\n";
        $ctrl .= "        return View::fetch('edit', ["."\n";
        $ctrl .= '            "entry" => $entry'."\n";
        $ctrl .= "        ]);"."\n";
        $ctrl .= "    }"."\n";
        $ctrl .= ""."\n";
        $ctrl .= '    public function list($'.$first_col.' = "", $page = 1, $limit = 20) {'."\n";
        $ctrl .= '        $query = " status=0 ";'."\n";
        $ctrl .= '        if (!empty($'.$first_col.')) {'."\n";
        $ctrl .= '            $query .= " and '.$first_col.' like \'%$'.$first_col.'%\' ";'."\n";
        $ctrl .= "        }"."\n";
        $ctrl .= ""."\n";
        $ctrl .= '        list($list, $count) = DataHelper::select_page("'.$tb_name.'", $query, [ "page" => $page, "limit" => $limit ]);'."\n";
        $ctrl .= '        if ($count <= 0) {'."\n";
        $ctrl .= "            return json([ 'code' => 201, 'msg' => '没有相关数据' ]);"."\n";
        $ctrl .= "        }"."\n";
        $ctrl .= '        return json([ \'code\' => 0, \'msg\' => \'成功\', \'count\' => $count, \'data\' => $list ]);'."\n";
        $ctrl .= "    }"."\n";
        $ctrl .= ""."\n";
        $ctrl .= "    public function del() {"."\n";
        $ctrl .= '        $params = get_all_params();'."\n";
        $ctrl .= '        $ids = $params[\'ids\'];'."\n";
        $ctrl .= '        DataHelper::update(\''.$tb_name.'\', "id in ($ids)", ['."\n";
        $ctrl .= "            'status' => -1"."\n";
        $ctrl .= "        ]);"."\n";
        $ctrl .= '        return json([ \'code\' => 0, \'msg\' => \'成功\' ]);'."\n";
        $ctrl .= "    }"."\n";
        $ctrl .= "}"."\n";


        $edit = '';
        $edit .= '<!DOCTYPE html>'."\n";
        $edit .= '<html>'."\n";
        $edit .= '<head>'."\n";
        $edit .= '    <meta charset="utf-8">'."\n";
        $edit .= '    <title>'.$objname.'</title>'."\n";
        $edit .= '    <meta name="renderer" content="webkit">'."\n";
        $edit .= '    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">'."\n";
        $edit .= '    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">'."\n";
        $edit .= '    <link rel="stylesheet" href="/static/layuiAdmin.std/src/layuiadmin/layui/css/layui.css" media="all">'."\n";
        $edit .= '    <link rel="stylesheet" href="/static/layuiAdmin.std/src/layuiadmin/style/admin.css" media="all">'."\n";
        $edit .= '</head>'."\n";
        $edit .= '<body>'."\n";
        $edit .= '<div class="layui-fluid">'."\n";
        $edit .= '    <div class="layui-row layui-col-space15">'."\n";
        $edit .= '        <div class="layui-col-md12">'."\n";
        $edit .= '            <div class="layui-card">'."\n";
        $edit .= '                <div class="layui-card-body">'."\n";
        $edit .= '                    <div class="layui-form">'."\n";
        $edit .= '                        <input type="hidden" id="id" name="id" value="{$entry.id}" />'."\n";

        foreach ($columns as $col) {
            if (in_array($col['Field'], ['id','status','create_time', 'update_time'])) {
                continue;
            }

            $edit .= '                        <div class="layui-form-item">' . "\n";
            $edit .= '                            <label class="layui-form-label">'.$col['Field'].'：</label>' . "\n";
            $edit .= '                            <div class="layui-input-block">' . "\n";
            $edit .= '                                <input type="text" id="'.$col['Field'].'" name="'.$col['Field'].'" value="{$entry.'.$col['Field'].'}"' . "\n";
            $edit .= '                                       lay-verify="required" placeholder="" autocomplete="off" class="layui-input">' . "\n";
            $edit .= '                            </div>' . "\n";
            $edit .= '                        </div>' . "\n";
        }

        $edit .= '                        <div class="layui-form-item">'."\n";
        $edit .= '                            <div class="layui-input-block">'."\n";
        $edit .= '                                <button class="layui-btn" lay-submit lay-filter="btn_save" id="btn_save">保存编辑</button>'."\n";
        $edit .= '                            </div>'."\n";
        $edit .= '                        </div>'."\n";
        $edit .= '                    </div>'."\n";
        $edit .= '                </div>'."\n";
        $edit .= '            </div>'."\n";
        $edit .= '        </div>'."\n";
        $edit .= '    </div>'."\n";
        $edit .= '</div>'."\n";
        $edit .= '<script src="/static/layuiAdmin.std/src/layuiadmin/layui/layui.js"></script>'."\n";
        $edit .= '<script>'."\n";
        $edit .= '    var tree;'."\n";
        $edit .= '    var layer;'."\n";
        $edit .= '    var util;'."\n";
        $edit .= '    var select;'."\n";
        $edit .= '    var $;'."\n";
        $edit .= '    var form;'."\n";
        $edit .= '    var layedit;'."\n";
        $edit .= ''."\n";
        $edit .= '    function save(field) {'."\n";
        $edit .= '        $(\'#btn_save\').hide()'."\n";
        $edit .= '        $.ajax({'."\n";
        $edit .= '            url: \'save\','."\n";
        $edit .= '            type: \'POST\','."\n";
        $edit .= '            data: field,'."\n";
        $edit .= '            dataType: \'json\','."\n";
        $edit .= '            success: function (data) {'."\n";
        $edit .= '                if (data.code == \'0\') {'."\n";
        $edit .= '                    layer.msg(\'保存成功\', { icon: 1, time: 2000 }, function () {'."\n";
        $edit .= '                        parent.layer.closeAll()'."\n";
        $edit .= '                        parent.$(\'#btnSearch\').click();'."\n";
        $edit .= '                        $(\'#btn_save\').show()'."\n";
        $edit .= '                    });'."\n";
        $edit .= '                } else {'."\n";
        $edit .= '                    layer.msg(data.msg, { icon: 5, time: 2000 });'."\n";
        $edit .= '                    $(\'#btn_save\').show()'."\n";
        $edit .= '                }'."\n";
        $edit .= '            }'."\n";
        $edit .= '        });'."\n";
        $edit .= '    }'."\n";
        $edit .= ''."\n";
        $edit .= '    layui.config({'."\n";
        $edit .= '        base: \'/static/layuiAdmin.std/src/layuiadmin/\' '."\n";
        $edit .= '    }).extend({'."\n";
        $edit .= '        index: \'lib/index\''."\n";
        $edit .= '    }).use([\'index\', \'tree\', \'util\', \'customSelect\', \'layedit\'], function(){'."\n";
        $edit .= '        tree = layui.tree'."\n";
        $edit .= '        layer = layui.layer'."\n";
        $edit .= '        util = layui.util'."\n";
        $edit .= '        select = layui.customSelect'."\n";
        $edit .= '        $ = layui.$'."\n";
        $edit .= '        form = layui.form'."\n";
        $edit .= '        layedit = layui.layedit;'."\n";
        $edit .= ''."\n";
        $edit .= '        form.on(\'submit(btn_save)\', function(obj){'."\n";
        $edit .= '            save(obj.field)'."\n";
        $edit .= '        });'."\n";
        $edit .= '    });'."\n";
        $edit .= '</script>'."\n";
        $edit .= '</body>'."\n";
        $edit .= '</html>'."\n";





        $index = '';
        $index .= '<!DOCTYPE html>'."\n";
        $index .= '<html>'."\n";
        $index .= '<head>'."\n";
        $index .= '    <meta charset="utf-8">'."\n";
        $index .= '    <title>'.$objname.'</title>'."\n";
        $index .= '    <meta name="renderer" content="webkit">'."\n";
        $index .= '    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">'."\n";
        $index .= '    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">'."\n";
        $index .= '    <link rel="stylesheet" href="/static/layuiAdmin.std/src/layuiadmin/layui/css/layui.css" media="all">'."\n";
        $index .= '    <link rel="stylesheet" href="/static/layuiAdmin.std/src/layuiadmin/style/admin.css" media="all">'."\n";
        $index .= '</head>'."\n";
        $index .= '<body>'."\n";
        $index .= '<div class="layui-fluid">'."\n";
        $index .= '    <div class="layui-card">'."\n";
        $index .= '        <div class="layui-form layui-card-header layuiadmin-card-header-auto">'."\n";
        $index .= '            <div class="layui-form-item">'."\n";
        $index .= '                <div class="layui-inline">'."\n";
        $index .= '                    <label class="layui-form-label">'.$first_col.'</label>'."\n";
        $index .= '                    <div class="layui-input-block">'."\n";
        $index .= '                        <input type="text" name="'.$first_col.'" placeholder="'.$first_col.'" autocomplete="off" class="layui-input">'."\n";
        $index .= '                    </div>'."\n";
        $index .= '                </div>'."\n";
        $index .= '                <div class="layui-inline">'."\n";
        $index .= '                    <button class="layui-btn" lay-submit lay-filter="btn-search" id="btnSearch">'."\n";
        $index .= '                        <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>'."\n";
        $index .= '                        搜索一下'."\n";
        $index .= '                    </button>'."\n";
        $index .= '                </div>'."\n";
        $index .= '            </div>'."\n";
        $index .= '        </div>'."\n";
        $index .= '        <div class="layui-card-body">'."\n";
        $index .= '            <div style="padding-bottom: 10px;">'."\n";
        $index .= '                <button class="layui-btn layui-btn-danger" onclick="del_batch()">批量删除</button>'."\n";
        $index .= '                <button class="layui-btn" onclick="add()">创建'.$objname.'</button>'."\n";
        $index .= '            </div>'."\n";
        $index .= '            <table id="TableList" lay-filter="TableList"></table>'."\n";
        $index .= '            <script type="text/html" id="imgTpl">'."\n";
        $index .= '                <img style="display: inline-block; width: 50%; height: 100%;" src= {{ d.avatar }}>'."\n";
        $index .= '            </script>'."\n";
        $index .= '            <script type="text/html" id="tools">'."\n";
        $index .= '                <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>'."\n";
        $index .= '                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>'."\n";
        $index .= '            </script>'."\n";
        $index .= '        </div>'."\n";
        $index .= '    </div>'."\n";
        $index .= '</div>'."\n";
        $index .= '<script src="/static/layuiAdmin.std/src/layuiadmin/layui/layui.js"></script>'."\n";
        $index .= '<script>'."\n";
        $index .= '    var $;'."\n";
        $index .= '    var form;'."\n";
        $index .= '    var table;'."\n";
        $index .= ''."\n";
        $index .= '    function add() {'."\n";
        $index .= '        layer.open({'."\n";
        $index .= '            type: 2'."\n";
        $index .= '            ,title: \'创建'.$objname.'\''."\n";
        $index .= '            ,content: \'edit?id=0\''."\n";
        $index .= '            ,maxmin: true'."\n";
        $index .= '            ,area: [\'90%\', \'90%\']'."\n";
        $index .= '        });'."\n";
        $index .= '    }'."\n";
        $index .= ''."\n";
        $index .= '    function edit(id) {'."\n";
        $index .= '        layer.open({'."\n";
        $index .= '            type: 2'."\n";
        $index .= '            ,title: \'编辑'.$objname.'\''."\n";
        $index .= '            ,content: \'edit?id=\' + id'."\n";
        $index .= '            ,maxmin: true'."\n";
        $index .= '            ,area: [\'90%\', \'90%\']'."\n";
        $index .= '        });'."\n";
        $index .= '    }'."\n";
        $index .= ''."\n";
        $index .= '    function del_batch() {'."\n";
        $index .= '        var checkStatus = table.checkStatus(\'TableList\')'."\n";
        $index .= '        var checkData = checkStatus.data;'."\n";
        $index .= '        if(checkData.length === 0){'."\n";
        $index .= '            return layer.msg(\'请选择数据\');'."\n";
        $index .= '        }'."\n";
        $index .= '        var ids = [];'."\n";
        $index .= '        for (var i = 0; i < checkData.length; i++) {'."\n";
        $index .= '            ids.push(checkData[i].id);'."\n";
        $index .= '        }'."\n";
        $index .= '        del(ids.join(\',\'))'."\n";
        $index .= '    }'."\n";
        $index .= ''."\n";
        $index .= '    function del(ids) {'."\n";
        $index .= '        layer.confirm(\'确定删除吗？\', function(index) {'."\n";
        $index .= '            $.ajax({'."\n";
        $index .= '                url: \'del\','."\n";
        $index .= '                type: \'POST\','."\n";
        $index .= '                data: {'."\n";
        $index .= '                    ids: ids'."\n";
        $index .= '                },'."\n";
        $index .= '                dataType: \'json\','."\n";
        $index .= '                success: function (data) {'."\n";
        $index .= '                    if (data.code == \'0\') {'."\n";
        $index .= '                        layer.msg(\'删除成功\', { icon: 1, time: 2000 }, function () {'."\n";
        $index .= '                            layer.closeAll()'."\n";
        $index .= '                            $(\'#btnSearch\').click();'."\n";
        $index .= '                        });'."\n";
        $index .= '                    } else {'."\n";
        $index .= '                        layer.msg(data.msg, { icon: 5, time: 2000 });'."\n";
        $index .= '                    }'."\n";
        $index .= '                }'."\n";
        $index .= '            });'."\n";
        $index .= '        });'."\n";
        $index .= '    }'."\n";
        $index .= ''."\n";
        $index .= '    layui.config({'."\n";
        $index .= '        base: \'/static/layuiAdmin.std/src/layuiadmin/\''."\n";
        $index .= '    }).extend({'."\n";
        $index .= '        index: \'lib/index\''."\n";
        $index .= '    }).use([\'index\', \'table\'], function(){'."\n";
        $index .= '        $ = layui.$'."\n";
        $index .= '        form = layui.form'."\n";
        $index .= '        table = layui.table;'."\n";
        $index .= ''."\n";
        $index .= '        table.render({'."\n";
        $index .= '            elem: \'#TableList\''."\n";
        $index .= '            ,url: \'list\''."\n";
        $index .= '            ,cols: [['."\n";
        $index .= '                {type: \'checkbox\', fixed: \'left\'}'."\n";
        $index .= '                ,{field: \'id\', width: 100, title: \'Id\', sort: true}'."\n";

        foreach ($columns as $col) {
            if (in_array($col['Field'], ['id','status','create_time', 'update_time'])) {
                continue;
            }

            $index .= '                ,{field: \''.$col['Field'].'\', title: \''.$col['Field'].'\'}'."\n";
        }



        $index .= '                ,{title: \'操作\', align:\'center\', fixed: \'right\', toolbar: \'#tools\'}'."\n";
        $index .= '            ]]'."\n";
        $index .= '            ,page: true'."\n";
        $index .= '            ,limit: 20'."\n";
        $index .= '            ,height: \'full-220\''."\n";
        $index .= '            ,text: \'对不起，加载出现异常！\''."\n";
        $index .= '        });'."\n";
        $index .= ''."\n";
        $index .= '        table.on(\'tool(TableList)\', function(obj){'."\n";
        $index .= '            var data = obj.data;'."\n";
        $index .= '            if(obj.event === \'del\'){'."\n";
        $index .= '                del(obj.data.id)'."\n";
        $index .= '            } else if(obj.event === \'edit\'){'."\n";
        $index .= '                edit(obj.data.id)'."\n";
        $index .= '            }'."\n";
        $index .= '        });'."\n";
        $index .= ''."\n";
        $index .= '        form.on(\'submit(btn-search)\', function(data){'."\n";
        $index .= '            var field = data.field;'."\n";
        $index .= '            table.reload(\'TableList\', {'."\n";
        $index .= '                where: field'."\n";
        $index .= '            });'."\n";
        $index .= '        });'."\n";
        $index .= '    });'."\n";
        $index .= '</script>'."\n";
        $index .= '</body>'."\n";
        $index .= '</html>'."\n";



        return json([ 'code' => 0, 'msg' => '成功', 'data' => [
            'ctrl' => $ctrl,
            'edit' => $edit,
            'index' => $index
        ] ]);
    }

    public function curd() {
        $table_list = Db::query("show tables");
        $tb_list = [];
        foreach ($table_list as $table_obj) {
            $table_name = strtolower($this->get_object_first_attribute($table_obj));
            $tb_list[] = $table_name;
        }

        return View::fetch('curd', [
            'tb_list' => $tb_list
        ]);
    }

    function get_object_first_attribute($object) {

        foreach ($object as $attr) {
            return $attr;
        }

        return '';
    }

    function tbname_to_objname($tb_name) {
        $rst = '';

        $rst = substr($tb_name, 3);
        $rst = str_replace("_", " ", $rst);
        $rst = ucwords($rst);
        $rst = str_replace(" ", "", $rst);

        return $rst;
    }

    public function setting() {
        $list = DataHelper::select('tb_setting', "status=0", [
            'order_by' => "id asc",
            'with_power' => false
        ]);

        return View::fetch('setting', [
            'list' => $list
        ]);
    }

    public function save_setting() {
        $params = get_all_params();

        foreach ($params as $key => $value) {
            DataHelper::update('tb_setting', "`key`='$key'", [
                'value' => $value
            ]);
        }


        return json([ 'code' => 0, 'msg' => '成功' ]);
    }
}